using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Threading.Tasks;
using GoChat_for_Windows.Models;
using GoChat_for_Windows.Utils;
using Newtonsoft.Json;

namespace GoChat_for_Windows.Services
{
    public class ApiService : IApiService
    {
        private readonly HttpClient _httpClient;
        private readonly ILocalStorageService _localStorageService;
        private const string BaseUrl = "http://121.199.21.194:3000/api/"; // 修改BaseUrl，确保以斜杠结尾

        public ApiService(ILocalStorageService localStorageService)
        {
            _localStorageService = localStorageService ?? throw new ArgumentNullException(nameof(localStorageService));
            _httpClient = new HttpClient
            {
                BaseAddress = new Uri(BaseUrl)
            };
        }

        private async Task EnsureAuthenticationAsync()
        {
            var token = await _localStorageService.GetTokenAsync();
            if (!string.IsNullOrEmpty(token))
            {
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            }
        }

        public async Task<User> LoginAsync(string username, string password)
        {
            ArgumentNullException.ThrowIfNull(username);
            ArgumentNullException.ThrowIfNull(password);

            try
            {
                // 对密码进行MD5加密
                string encryptedPassword = PasswordUtils.EncryptPassword(password);

                var response = await _httpClient.PostAsJsonAsync("users/login", new
                {
                    username,
                    password = encryptedPassword
                });

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    var user = JsonConvert.DeserializeObject<User>(content);
                    return user ?? throw new Exception("服务器返回的用户数据无效");
                }

                throw new Exception(await response.Content.ReadAsStringAsync());
            }
            catch (Exception ex)
            {
                throw new Exception($"登录失败: {ex.Message}");
            }
        }

        public async Task<bool> RegisterAsync(string username, string password, string nickname)
        {
            ArgumentNullException.ThrowIfNull(username);
            ArgumentNullException.ThrowIfNull(password);
            ArgumentNullException.ThrowIfNull(nickname);

            try
            {
                // 对密码进行MD5加密
                string encryptedPassword = PasswordUtils.EncryptPassword(password);

                var response = await _httpClient.PostAsJsonAsync("users/register", new
                {
                    username,
                    password = encryptedPassword,
                    nickname
                });

                if (response.IsSuccessStatusCode)
                {
                    return true;
                }

                throw new Exception(await response.Content.ReadAsStringAsync());
            }
            catch (Exception ex)
            {
                throw new Exception($"注册失败: {ex.Message}");
            }
        }

        public async Task<bool> UpdateUserProfileAsync(User user)
        {
            try
            {
                var response = await _httpClient.PutAsJsonAsync($"users/{user.Id}", user);
                return response.IsSuccessStatusCode;
            }
            catch (Exception ex)
            {
                throw new Exception($"更新用户信息失败: {ex.Message}");
            }
        }

        public async Task<List<User>> GetUserListAsync()
        {
            try
            {
                var response = await _httpClient.GetAsync("users");
                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    var users = JsonConvert.DeserializeObject<List<User>>(content);
                    return users ?? new List<User>();
                }

                throw new Exception(await response.Content.ReadAsStringAsync());
            }
            catch (Exception ex)
            {
                throw new Exception($"获取用户列表失败: {ex.Message}");
            }
        }

        public async Task<List<Message>> GetMessageHistoryAsync(int senderId, int receiverId, int pageSize, int pageNumber)
        {
            await EnsureAuthenticationAsync();
            var response = await _httpClient.GetAsync($"messages/history/{senderId}?targetUserId={receiverId}&page={pageNumber}&limit={pageSize}");
            response.EnsureSuccessStatusCode();
            var messages = await response.Content.ReadFromJsonAsync<List<Message>>();
            return messages ?? new List<Message>();
        }

        public async Task<bool> SendMessageAsync(Message message)
        {
            await EnsureAuthenticationAsync();
            var response = await _httpClient.PostAsJsonAsync("messages", message);
            return response.IsSuccessStatusCode;
        }

        public async Task<bool> MarkMessageAsReadAsync(int messageId)
        {
            try
            {
                var response = await _httpClient.PutAsync($"/messages/{messageId}/read", null);
                return response.IsSuccessStatusCode;
            }
            catch (Exception ex)
            {
                throw new Exception($"标记消息已读失败: {ex.Message}");
            }
        }

        public async Task<string> UploadFileAsync(string filePath, string fileType)
        {
            ArgumentNullException.ThrowIfNull(filePath);
            ArgumentNullException.ThrowIfNull(fileType);
            await EnsureAuthenticationAsync();

            using var form = new MultipartFormDataContent();
            using var fileStream = File.OpenRead(filePath);
            using var streamContent = new StreamContent(fileStream);
            
            streamContent.Headers.ContentType = new MediaTypeHeaderValue(fileType);
            form.Add(streamContent, "file", Path.GetFileName(filePath));

            string uploadEndpoint = fileType.StartsWith("image/") ? "upload" :
                                  fileType.StartsWith("audio/") ? "upload/audio" :
                                  fileType.StartsWith("video/") ? "upload/video" :
                                  "upload/file";

            var response = await _httpClient.PostAsync(uploadEndpoint, form);
            response.EnsureSuccessStatusCode();
            
            var result = await response.Content.ReadAsStringAsync();
            var fileInfo = JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
            return fileInfo?["url"] ?? throw new Exception("文件上传失败");
        }

        public async Task<bool> DownloadFileAsync(string fileUrl, string savePath, IProgress<double> progress)
        {
            await EnsureAuthenticationAsync();

            using var response = await _httpClient.GetAsync(fileUrl, HttpCompletionOption.ResponseHeadersRead);
            response.EnsureSuccessStatusCode();

            var totalBytes = response.Content.Headers.ContentLength ?? -1L;
            using var contentStream = await response.Content.ReadAsStreamAsync();
            using var fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true);

            var buffer = new byte[8192];
            var totalBytesRead = 0L;
            var bytesRead = 0;

            while ((bytesRead = await contentStream.ReadAsync(buffer)) != 0)
            {
                await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead));
                totalBytesRead += bytesRead;

                if (totalBytes != -1L)
                {
                    var progressPercentage = (double)totalBytesRead / totalBytes;
                    progress.Report(progressPercentage);
                }
            }

            return true;
        }

        public async Task<bool> UpdateUserStatusAsync(string status)
        {
            try
            {
                var response = await _httpClient.PutAsJsonAsync("users/status", new { status });
                return response.IsSuccessStatusCode;
            }
            catch (Exception ex)
            {
                throw new Exception($"更新状态失败: {ex.Message}");
            }
        }

        public async Task<bool> HeartbeatAsync()
        {
            try
            {
                var response = await _httpClient.PostAsync("users/heartbeat", null);
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }

        private class FileUploadResult
        {
            public string Url { get; set; } = string.Empty;
        }
    }
} 